package com.tzstcl.sys.user.ctrl;


import com.tzstcl.base.ctrl.BaseCtrl;
import com.tzstcl.base.model.AjaxResult;
import com.tzstcl.commons.utils.IpUtils;
import com.tzstcl.framework.constants.AppConstants;
import com.tzstcl.framework.redis.RedisService;
import com.tzstcl.framework.shiro.ShiroUtils;
import com.tzstcl.sys.user.model.SysUser;
import com.tzstcl.sys.user.service.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 登录控制器
 *
 * @author haocj
 */
@Controller
@RequestMapping("/admin")
public class LoginCtrl extends BaseCtrl {


    @Autowired
    private RedisService redisService;
    @Autowired
    private SysUserService sysUserService;


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult login(SysUser sysUser, HttpServletRequest request) {
        Subject subject = ShiroUtils.getSubjct();
        String password = new Sha256Hash(sysUser.getPassword()).toHex();
        UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getLoginName(), password);
        try {
            subject.login(token);

        } catch (AuthenticationException e) {
            e.printStackTrace();
            return error(e.getMessage());
        }

        SysUser user = ShiroUtils.getUser();
        if (null != user) {
            user.setLoginDate(new Date());
            String ipAddr = IpUtils.getIpAddr(request);
            user.setLoginIp(ipAddr);
            sysUserService.update(user);
        }
        return success(AppConstants.SUCCESS_MSG);
    }
}
